package linker;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import linker.exception.CanNotCreateSocketException;
import linker.exception.CanNotReadObjectException;
import linker.exception.CanNotWriteObjectException;
import linker.exception.ErrorClosingSocketException;

public class ClientLinker {
	
	private Socket				clientSocket;
	private ObjectInputStream	in;
	private ObjectOutput		out;
	
	public ClientLinker(Socket client) throws IOException {

		this.clientSocket = client;
		System.out.println("Client socket created.");
		this.in = new ObjectInputStream(this.clientSocket.getInputStream());
		System.out.println("Client in Stub created.");
		this.out = new ObjectOutputStream(this.clientSocket.getOutputStream());
		System.out.println("Client out Stub created.");
	}
	
	public ClientLinker(String ip, int port) throws CanNotCreateSocketException {

		try {
			this.clientSocket = new Socket(InetAddress.getByName(ip), port);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			throw new CanNotCreateSocketException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new CanNotCreateSocketException(e);
		}
	}
	
	public void close() throws ErrorClosingSocketException {

		try {
			this.clientSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new ErrorClosingSocketException(e);
		}
	}
	
	public Object readObject() throws CanNotReadObjectException {

		try {
			return this.in.readObject();
		} catch (IOException e) {
			e.printStackTrace();
			throw new CanNotReadObjectException(e);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new CanNotReadObjectException(e);
		}
	}
	
	public void writeObject(Object obj) throws CanNotWriteObjectException {

		try {
			this.out.writeObject(obj);
		} catch (IOException e) {
			e.printStackTrace();
			throw new CanNotWriteObjectException(e);
		}
		
	}
}
